package org.lee.framework.web;

import lombok.extern.slf4j.Slf4j;
import org.lee.common.core.vo.response.AjaxResult;
import org.lee.common.exception.ServiceException;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

/**
 * 统一异常处理
 *
 * @author ltb
 */
@Slf4j
@Component
public class AppRouterInterceptor implements RouterInterceptor {
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        try {
            chain.doIntercept(ctx, mainHandler);
            if (mainHandler == null) {
                ctx.render(AjaxResult.error(404, "资源不存在"));
            }
        } catch (ServiceException e) {
            ctx.render(AjaxResult.error(e.getCode(), e.getMessage()));
        } catch (RuntimeException e) {
            log.error("请求地址'{}',异常信息: {}.", ctx.uri().getPath(), e.getMessage());
            ctx.render(AjaxResult.error(e.getMessage())); //e.getResult().getDescription()
        } catch (Throwable e) {
            ctx.render(AjaxResult.error(500, "服务端运行出错"));
        }
    }
} 